#include "content.h"
#include "ui_content.h"
#include "api.h"
#include <QMessageBox>
#include <QDate>
#include <QLabel>
#include <QRandomGenerator>
#include <QFormLayout>
#include <QDateEdit>
#include <QTextEdit>

content::content(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::content)
    , m_gameContentCurrentPage(1)
    , m_gameContentPageSize(10)
    , m_announcementCurrentPage(1)
    , m_announcementPageSize(10)
    , m_gameContentTotalCount(0)
    , m_announcementTotalCount(0)
    , m_gameContentSearchKeyword("")
    , m_gameContentSearchCategory("")
    , m_gameContentSearchStatus("")
    , m_gameContentSearchDateStart("")
    , m_gameContentSearchDateEnd("")
    , m_announcementSearchKeyword("")
    , m_announcementSearchStatus("")
{
    ui->setupUi(this);
    initUI();
}

content::~content()
{
    delete ui;
}

void content::initUI()
{
    // 初始化UI相关设置
    ui->gameContentPageSpinBox->setMinimum(0);
    ui->announcementPageSpinBox->setMinimum(0);

    // 默认显示游戏内容标签页
    // updateGameContentTable();
    on_gameContentSearchButton_clicked();
}

void content::updateGameContentTable()
{
    // 更新游戏内容表格
    fetchGameContents();
}

void content::handleGameContentDataFetched(bool success, const QJsonObject& response)
{
    showLoadingIndicator(false);
    
    if (!success) {
        handleGameContentError("获取游戏内容失败");
        return;
    }
    
    // 清空表格
    ui->gameContentTableWidget->clearContents();
    ui->gameContentTableWidget->setRowCount(0);
    
    try {
        // 获取数据列表
        QJsonArray dataArray = response["data"].toObject()["list"].toArray();
        
        // 设置总数量
        m_gameContentTotalCount = response["data"].toObject()["total"].toInt();
        
        // 更新分页信息
        updateGameContentPaginationInfo();
        
        // 填充表格数据
        for (int i = 0; i < dataArray.size(); ++i) {
            QJsonObject item = dataArray[i].toObject();
            
            // 创建新行
            int row = ui->gameContentTableWidget->rowCount();
            ui->gameContentTableWidget->insertRow(row);
            
            // 添加数据到表格，确保字段映射正确
            ui->gameContentTableWidget->setItem(row, 0, createNonEditableItem(item["id"].toString()));
            ui->gameContentTableWidget->setItem(row, 1, createNonEditableItem(item["title"].toString()));
            ui->gameContentTableWidget->setItem(row, 2, createNonEditableItem(item["category"].toString()));
            
            // 使用publishDate字段作为发布日期
            QString publishDate = item.contains("publishDate") ? item["publishDate"].toString() : "";
            ui->gameContentTableWidget->setItem(row, 3, createNonEditableItem(publishDate));
            
            // 设置状态（字符串形式）
            ui->gameContentTableWidget->setItem(row, 4, createStatusItem(item["status"].toString(), true));
        }
        
    } catch (const std::exception& e) {
        handleGameContentError(QString("处理数据时出错: ") + e.what());
    } catch (...) {
        handleGameContentError("处理数据时发生未知错误");
    }
}

void content::handleGameContentError(const QString& errorMsg)
{
    showLoadingIndicator(false);
    QMessageBox::warning(this, "错误", errorMsg);
}

void content::updateAnnouncementTable()
{
    // 更新公告表格
    fetchAnnouncements();
}

void content::fetchAnnouncements()
{
    // 显示加载指示器
    showLoadingIndicator(true);
    
    // 准备搜索参数
    QJsonObject params = prepareAnnouncementSearchParams();
    
    // 调用API获取公告数据
    Api::getInstance()->getAnnouncements(params, [this](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        // 隐藏加载指示器
        showLoadingIndicator(false);
        
        if (success) {
            QJsonObject data = response["data"].toObject();
            
            // 检查数据是否有效（包含必要字段且列表不为空）
            if (data.contains("total") && data.contains("list") && data["list"].isArray() && !data["list"].toArray().isEmpty()) {
                // 更新总数量
                m_announcementTotalCount = data["total"].toInt();
                
                // 使用真实数据
                handleAnnouncementDataFetched(true, response);
                return;
            }
            
            // 数据为空或不完整，使用模拟数据
            QMessageBox::warning(this, "数据获取提示", "获取到的数据为空或不完整，正在使用模拟数据进行展示。");
        } else {
            // API调用失败，显示错误信息并使用模拟数据
            QString errorMessage = errorMsg.isEmpty() ? "网络请求失败或服务器无响应" : errorMsg;
            QMessageBox::warning(this, "数据获取失败", QString("无法获取公告数据: %1\n\n正在使用模拟数据进行展示。").arg(errorMessage));
        }
        
        // 生成模拟数据
        QJsonObject mockResponse;
        mockResponse["success"] = true;
        
        QJsonObject mockData;
        mockData["total"] = 15; // 模拟总数据量
        
        // 准备所有模拟数据
        QJsonArray allMockItems;
        for (int i = 0; i < 15; i++) {
            QJsonObject item;
            item["id"] = QString::number(2000 + i);
            item["title"] = QString("模拟公告标题 %1").arg(i + 1);
            
            // 随机分配状态
            QStringList statuses = {"已发布", "草稿", "已过期"};
            QString status = statuses[QRandomGenerator::global()->bounded(3)];
            item["status"] = status;
            
            // 添加发布时间和过期时间
            QDate publishDate = QDate::currentDate().addDays(-QRandomGenerator::global()->bounded(30));
            item["publishDate"] = publishDate.toString("yyyy-MM-dd");
            
            QDate expireDate = publishDate.addDays(7 + QRandomGenerator::global()->bounded(23)); // 7-30天后过期
            item["expireDate"] = expireDate.toString("yyyy-MM-dd");
            
            // 添加公告内容
            item["content"] = QString("这是公告ID为%1的详细内容。\n\n此处包含公告的完整文本信息，可以有多行内容，展示公告的全部细节。").arg(2000 + i);
            
            allMockItems.append(item);
        }
        
        // 根据分页参数过滤数据
        QJsonArray mockList;
        int startIndex = (m_announcementCurrentPage - 1) * m_announcementPageSize;
        int endIndex = qMin(startIndex + m_announcementPageSize, allMockItems.size());
        
        for (int i = startIndex; i < endIndex; i++) {
            mockList.append(allMockItems.at(i));
        }
        
        mockData["list"] = mockList;
        mockResponse["data"] = mockData;
        
        // 更新总数量
        m_announcementTotalCount = mockData["total"].toInt();
        
        // 使用模拟数据
        handleAnnouncementDataFetched(true, mockResponse);
    });
}

void content::handleAnnouncementDataFetched(bool success, const QJsonObject& response)
{
    showLoadingIndicator(false);
    
    if (!success) {
        handleAnnouncementError("获取公告失败");
        return;
    }
    
    // 清空表格
    ui->announcementTableWidget->clearContents();
    ui->announcementTableWidget->setRowCount(0);
    
    try {
        // 获取数据列表
        QJsonArray dataArray = response["data"].toObject()["list"].toArray();
        
        // 更新总数量
        m_announcementTotalCount = response["data"].toObject()["total"].toInt();
        
        // 更新分页信息
        updateAnnouncementPaginationInfo();
        
        // 填充表格数据 - 考虑分页，只处理当前页应显示的数据
        for (int i = 0; i < dataArray.size(); ++i) {
            QJsonObject item = dataArray[i].toObject();
            
            // 创建新行
            int row = ui->announcementTableWidget->rowCount();
            ui->announcementTableWidget->insertRow(row);
            
            // 添加数据到表格
            ui->announcementTableWidget->setItem(row, 0, createNonEditableItem(item["id"].toString()));
            ui->announcementTableWidget->setItem(row, 1, createNonEditableItem(item["title"].toString()));
            ui->announcementTableWidget->setItem(row, 2, createNonEditableItem(item["publishDate"].toString()));
            ui->announcementTableWidget->setItem(row, 3, createNonEditableItem(item["expireDate"].toString()));
            ui->announcementTableWidget->setItem(row, 4, createStatusItem(item["status"].toString(), false));
            
            // 添加操作按钮 - 查看内容
            QPushButton* viewButton = new QPushButton("查看内容");
            connect(viewButton, &QPushButton::clicked, this, [this, item]() {
                showAnnouncementDetail(item);
            });
            ui->announcementTableWidget->setCellWidget(row, 5, viewButton);
        }
        
    } catch (const std::exception& e) {
        handleAnnouncementError(QString("处理数据时出错: ") + e.what());
    } catch (...) {
        handleAnnouncementError("处理数据时发生未知错误");
    }
}

void content::handleAnnouncementError(const QString& errorMsg)
{
    showLoadingIndicator(false);
    QMessageBox::warning(this, "错误", errorMsg);
}

QJsonObject content::prepareAnnouncementSearchParams()
{
    // 准备公告搜索参数
    QJsonObject params;
    params["page"] = QString::number(m_announcementCurrentPage);
    params["pageSize"] = QString::number(m_announcementPageSize);
    params["keyword"] = m_announcementSearchKeyword;
    params["status"] = m_announcementSearchStatus;
    
    return params;
}

void content::showAnnouncementDetail(const QJsonObject& announcementData)
{
    // 创建详细信息对话框
    QDialog* detailDialog = new QDialog(this);
    detailDialog->setWindowTitle("公告详情");
    detailDialog->resize(600, 400);
    detailDialog->setModal(true); // 模态对话框，阻止用户在查看详情时与主界面交互
    
    // 创建垂直布局
    QVBoxLayout* mainLayout = new QVBoxLayout(detailDialog);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    
    // 标题
    QLabel* titleLabel = new QLabel(detailDialog);
    titleLabel->setText(announcementData["title"].toString());
    titleLabel->setStyleSheet("font-size: 18px; font-weight: bold; margin-bottom: 10px;");
    titleLabel->setWordWrap(true);
    
    // 信息栏
    QLabel* infoLabel = new QLabel(detailDialog);
    QString statusText = announcementData["status"].toString();
    QString infoText = QString("状态: %1  |  发布日期: %2  |  过期日期: %3")
        .arg(statusText)
        .arg(announcementData["publishDate"].toString())
        .arg(announcementData["expireDate"].toString());
    infoLabel->setText(infoText);
    infoLabel->setStyleSheet("color: #666; margin-bottom: 15px;");
    
    // 内容区域
    QTextEdit* contentTextEdit = new QTextEdit(detailDialog);
    contentTextEdit->setText(announcementData["content"].toString());
    contentTextEdit->setReadOnly(true);
    contentTextEdit->setLineWrapMode(QTextEdit::WidgetWidth);
    contentTextEdit->setStyleSheet("background-color: #f5f5f5; padding: 10px;");
    
    // 关闭按钮
    QPushButton* closeButton = new QPushButton("关闭", detailDialog);
    closeButton->setStyleSheet("padding: 5px 15px; max-width: 100px;");
    connect(closeButton, &QPushButton::clicked, detailDialog, &QDialog::accept);
    
    // 添加组件到布局
    mainLayout->addWidget(titleLabel);
    mainLayout->addWidget(infoLabel);
    mainLayout->addWidget(contentTextEdit);
    mainLayout->addWidget(closeButton, 0, Qt::AlignRight);
    
    // 显示对话框
    detailDialog->exec();
    
    // 清理资源
    detailDialog->deleteLater();
}

void content::updateGameContentPaginationInfo()
{
    // 更新游戏内容分页信息
    int totalPages = (m_gameContentTotalCount + m_gameContentPageSize - 1) / m_gameContentPageSize;
    
    ui->gameContentPageSpinBox->setMaximum(qMax(1, totalPages));
    ui->gameContentPageInfoLabel->setText(QString("第 %1 页 / 共 %2 页  共 %3 条数据").arg(m_gameContentCurrentPage).arg(totalPages).arg(m_gameContentTotalCount));
    
    // 更新按钮状态
    ui->gameContentPrevPageButton->setEnabled(m_gameContentCurrentPage > 1);
    ui->gameContentNextPageButton->setEnabled(m_gameContentCurrentPage < totalPages);
}



void content::updateAnnouncementPaginationInfo()
{
    // 更新公告分页信息
    int totalPages = (m_announcementTotalCount + m_announcementPageSize - 1) / m_announcementPageSize;
    
    ui->announcementPageSpinBox->setMaximum(qMax(1, totalPages));
    ui->announcementPageInfoLabel->setText(QString("第 %1 页 / 共 %2 页  共 %3 条数据").arg(m_announcementCurrentPage).arg(totalPages).arg(m_announcementTotalCount));
    
    // 更新按钮状态
    ui->announcementPrevPageButton->setEnabled(m_announcementCurrentPage > 1);
    ui->announcementNextPageButton->setEnabled(m_announcementCurrentPage < totalPages);
}


void content::fetchGameContents()
{
    // 显示加载指示器
    showLoadingIndicator(true);
    
    // 准备搜索参数
    QJsonObject params = prepareGameContentSearchParams();
    
    // 调用API获取游戏内容数据
    Api::getInstance()->getGameContents(params, [this](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        // 隐藏加载指示器
        showLoadingIndicator(false);
        
        if (success) {
            QJsonObject data = response["data"].toObject();
            
            // 检查数据是否有效（包含必要字段且列表不为空）
            if (data.contains("total") && data.contains("list") && data["list"].isArray() && !data["list"].toArray().isEmpty()) {
                // 更新总数量
                m_gameContentTotalCount = data["total"].toInt();
                
                // 使用真实数据
                handleGameContentDataFetched(true, response);
                return;
            }
            
            // 数据为空或不完整，使用模拟数据
            QMessageBox::warning(this, "数据获取提示", "获取到的数据为空或不完整，正在使用模拟数据进行展示。");
        } else {
            // API调用失败，显示错误信息并使用模拟数据
            QString errorMessage = errorMsg.isEmpty() ? "网络请求失败或服务器无响应" : errorMsg;
            QMessageBox::warning(this, "数据获取失败", QString("无法获取游戏内容数据: %1\n\n正在使用模拟数据进行展示。").arg(errorMessage));
        }
        
        // 生成模拟数据
        QJsonObject mockResponse;
        mockResponse["success"] = true;
        
        QJsonObject mockData;
        mockData["total"] = 20; // 模拟总数据量
        
        QJsonArray mockList;
        
        // 生成10条模拟数据
        for (int i = 0; i < 10; i++) {
            QJsonObject item;
            item["id"] = QString::number(1000 + i);
            item["title"] = QString("模拟游戏内容 %1").arg(i + 1);
            
            // 随机分配类别
            QStringList categories = {"游戏", "视频", "文章"};
            item["category"] = categories[QRandomGenerator::global()->bounded(3)];
            
            // 随机分配状态
            QStringList statuses = {"已发布", "草稿", "已下架"};
            QString status = statuses[QRandomGenerator::global()->bounded(3)];
            item["status"] = status;
            
            // 添加发布时间
            QDate date = QDate::currentDate().addDays(-QRandomGenerator::global()->bounded(30));
            item["publishDate"] = date.toString("yyyy-MM-dd");
            
            // 添加浏览量和下载量
            item["views"] = QRandomGenerator::global()->bounded(10000);
            item["downloads"] = QRandomGenerator::global()->bounded(5000);
            
            // 添加描述
            item["description"] = QString("这是一条模拟的游戏内容描述信息，内容ID: %1").arg(1000 + i);
            
            mockList.append(item);
        }
        
        mockData["list"] = mockList;
        mockResponse["data"] = mockData;
        
        // 更新总数量
        m_gameContentTotalCount = mockData["total"].toInt();
        
        // 使用模拟数据
        handleGameContentDataFetched(true, mockResponse);
    });
}

QJsonObject content::prepareGameContentSearchParams()
{
    // 准备游戏内容搜索参数
    QJsonObject params;
    params["page"] = QString::number(m_gameContentCurrentPage);
    params["pageSize"] = QString::number(m_gameContentPageSize);
    params["keyword"] = m_gameContentSearchKeyword;
    params["category"] = m_gameContentSearchCategory;
    params["status"] = m_gameContentSearchStatus;
    
    return params;
}

void content::showLoadingIndicator(bool show)
{
    // 显示或隐藏加载指示器
    if (show) {
        // TODO: 实现加载指示器显示
    } else {
        // TODO: 实现加载指示器隐藏
    }
}

QString content::getStatusText(const QString& status, bool isGameContent)
{
    // 直接返回字符串状态
    if (isGameContent) {
        if (status == "已发布" || status == "草稿" || status == "已下架") {
            return status;
        } else {
            return "未知";
        }
    } else {
        if (status == "已发布" || status == "草稿" || status == "已过期") {
            return status;
        } else {
            return "未知";
        }
    }
}

QTableWidgetItem* content::createNonEditableItem(const QString& text)
{
    QTableWidgetItem *item = new QTableWidgetItem(text);
    item->setFlags(item->flags() & ~Qt::ItemIsEditable);
    return item;
}

QTableWidgetItem* content::createStatusItem(const QString& status, bool isGameContent)
{
    QTableWidgetItem *item = new QTableWidgetItem(getStatusText(status, isGameContent));
    item->setFlags(item->flags() & ~Qt::ItemIsEditable);
    
    // 设置不同状态的文本颜色
    QColor color;
    if (status == "已发布") {
        color = Qt::darkGreen; // 已发布
    } else if (status == "草稿") {
        color = Qt::darkYellow; // 草稿
    } else if (status == "已下架" || status == "已过期") {
        color = Qt::gray; // 已下架/已过期
    } else {
        color = Qt::black; // 未知
    }
    
    item->setForeground(color);
    return item;
}

// 游戏内容相关槽函数
void content::on_addGameContentButton_clicked()
{
    // 创建添加游戏内容对话框
    QDialog* addDialog = new QDialog(this);
    addDialog->setWindowTitle("添加游戏内容");
    addDialog->resize(500, 400);
    
    // 创建布局
    QVBoxLayout* mainLayout = new QVBoxLayout(addDialog);
    
    // 创建表单布局
    QFormLayout* formLayout = new QFormLayout();
    
    // 游戏标题
    QLineEdit* titleEdit = new QLineEdit();
    titleEdit->setPlaceholderText("请输入游戏标题");
    formLayout->addRow("游戏标题:", titleEdit);
    
    // 游戏分类
    QComboBox* categoryComboBox = new QComboBox();
    categoryComboBox->addItem("角色扮演", "角色扮演");
    categoryComboBox->addItem("动作冒险", "动作冒险");
    categoryComboBox->addItem("策略", "策略");
    categoryComboBox->addItem("模拟", "模拟");
    formLayout->addRow("游戏分类:", categoryComboBox);
    
    // 发布日期
    QDateEdit* publishDateEdit = new QDateEdit();
    publishDateEdit->setCalendarPopup(true);
    publishDateEdit->setDate(QDate::currentDate());
    formLayout->addRow("发布日期:", publishDateEdit);
    
    // 游戏状态
    QComboBox* statusComboBox = new QComboBox();
    statusComboBox->addItem("已发布", "已发布");
    statusComboBox->addItem("草稿", "草稿");
    formLayout->addRow("内容状态:", statusComboBox);
    
    // 游戏描述
    QTextEdit* descriptionEdit = new QTextEdit();
    descriptionEdit->setPlaceholderText("请输入游戏描述信息");
    formLayout->addRow("游戏描述:", descriptionEdit);
    
    // 添加表单到主布局
    mainLayout->addLayout(formLayout);
    
    // 创建按钮布局
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    
    // 添加按钮
    QPushButton* confirmButton = new QPushButton("确认添加");
    QPushButton* cancelButton = new QPushButton("取消");
    
    buttonLayout->addWidget(confirmButton);
    buttonLayout->addWidget(cancelButton);
    
    mainLayout->addLayout(buttonLayout);
    
    // 连接取消按钮信号
    connect(cancelButton, &QPushButton::clicked, addDialog, &QDialog::reject);
    
    // 连接确认按钮信号
    connect(confirmButton, &QPushButton::clicked, [=]() {
        // 验证输入
        if (titleEdit->text().trimmed().isEmpty()) {
            QMessageBox::warning(addDialog, "输入错误", "游戏标题不能为空！");
            titleEdit->setFocus();
            return;
        }
        
        // 准备参数
        QJsonObject params;
        params["title"] = titleEdit->text().trimmed();
        params["category"] = categoryComboBox->currentData().toString();
        params["publishDate"] = publishDateEdit->date().toString("yyyy-MM-dd");
        params["status"] = statusComboBox->currentData().toString();
        params["description"] = descriptionEdit->toPlainText().trimmed();

        
        // 调用API添加游戏内容
        Api::getInstance()->addGameContent(params, [=](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
            if (success) {
                // 添加成功
                QMessageBox::information(addDialog, "添加成功", "游戏内容添加成功！");
                addDialog->accept();
                
                // 刷新游戏内容列表
                this->updateGameContentTable();
            } else {
                // 添加失败
                QString errorMessage = errorMsg.isEmpty() ? "添加游戏内容失败，请稍后重试" : errorMsg;
                QMessageBox::warning(addDialog, "添加失败", errorMessage);
            }
        });
    });
    
    // 显示对话框
    if (addDialog->exec() == QDialog::Accepted) {
        // 对话框接受时的处理（已在回调中处理）
    }
    
    // 清理资源
    delete addDialog;
}

void content::on_editGameContentButton_clicked()
{
    // 获取选中的行
    QModelIndexList selectedRows = ui->gameContentTableWidget->selectionModel()->selectedRows();
    
    if (selectedRows.isEmpty()) {
        QMessageBox::warning(this, "提示", "请先选择要编辑的游戏内容！");
        return;
    }
    
    // 获取选中行的数据
    int selectedRow = selectedRows.first().row();
    QString contentId = ui->gameContentTableWidget->item(selectedRow, 0)->text();
    QString gameTitle = ui->gameContentTableWidget->item(selectedRow, 1)->text();
    QString gameCategory = ui->gameContentTableWidget->item(selectedRow, 2)->text();
    QString publishDate = ui->gameContentTableWidget->item(selectedRow, 3)->text();
    QString gameStatus = ui->gameContentTableWidget->item(selectedRow, 4)->text();
    
    // 创建编辑对话框
    QDialog* editDialog = new QDialog(this);
    editDialog->setWindowTitle("编辑游戏内容");
    editDialog->resize(500, 400);
    
    // 创建布局
    QVBoxLayout* mainLayout = new QVBoxLayout(editDialog);
    
    // 创建表单布局
    QFormLayout* formLayout = new QFormLayout();
    
    // 游戏标题
    QLineEdit* titleEdit = new QLineEdit();
    titleEdit->setText(gameTitle);
    titleEdit->setPlaceholderText("请输入游戏标题");
    formLayout->addRow("游戏标题:", titleEdit);
    
    // 游戏分类
    QComboBox* categoryComboBox = new QComboBox();
    categoryComboBox->addItem("角色扮演", "角色扮演");
    categoryComboBox->addItem("动作冒险", "动作冒险");
    categoryComboBox->addItem("策略", "策略");
    categoryComboBox->addItem("模拟", "模拟");
    // 设置当前选中的分类
    for (int i = 0; i < categoryComboBox->count(); i++) {
        if (categoryComboBox->itemData(i).toString() == gameCategory) {
            categoryComboBox->setCurrentIndex(i);
            break;
        }
    }
    formLayout->addRow("游戏分类:", categoryComboBox);
    
    // 发布日期
    QDateEdit* publishDateEdit = new QDateEdit();
    publishDateEdit->setCalendarPopup(true);
    QDate date = QDate::fromString(publishDate, "yyyy-MM-dd");
    if (date.isValid()) {
        publishDateEdit->setDate(date);
    } else {
        publishDateEdit->setDate(QDate::currentDate());
    }
    formLayout->addRow("发布日期:", publishDateEdit);
    
    // 游戏状态
    QComboBox* statusComboBox = new QComboBox();
    statusComboBox->addItem("已发布", "已发布");
    statusComboBox->addItem("草稿", "草稿");
    statusComboBox->addItem("已下架", "已下架");
    // 设置当前选中的状态
    for (int i = 0; i < statusComboBox->count(); i++) {
        if (statusComboBox->itemData(i).toString() == gameStatus) {
            statusComboBox->setCurrentIndex(i);
            break;
        }
    }
    formLayout->addRow("内容状态:", statusComboBox);
    
    // 游戏描述
    QTextEdit* descriptionEdit = new QTextEdit();
    descriptionEdit->setPlaceholderText("请输入游戏描述信息");
    formLayout->addRow("游戏描述:", descriptionEdit);
    
    // 添加表单到主布局
    mainLayout->addLayout(formLayout);
    
    // 创建按钮布局
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    
    // 添加按钮
    QPushButton* confirmButton = new QPushButton("确认修改");
    QPushButton* cancelButton = new QPushButton("取消");
    
    buttonLayout->addWidget(confirmButton);
    buttonLayout->addWidget(cancelButton);
    
    mainLayout->addLayout(buttonLayout);
    
    // 连接取消按钮信号
    connect(cancelButton, &QPushButton::clicked, editDialog, &QDialog::reject);
    
    // 连接确认按钮信号
    connect(confirmButton, &QPushButton::clicked, [=]() {
        // 验证输入
        if (titleEdit->text().trimmed().isEmpty()) {
            QMessageBox::warning(editDialog, "输入错误", "游戏标题不能为空！");
            titleEdit->setFocus();
            return;
        }
        
        // 准备参数
        QJsonObject params;
        params["id"] = contentId;
        params["title"] = titleEdit->text().trimmed();
        params["category"] = categoryComboBox->currentData().toString();
        params["publishDate"] = publishDateEdit->date().toString("yyyy-MM-dd");
        params["status"] = statusComboBox->currentData().toString();
        params["description"] = descriptionEdit->toPlainText().trimmed();
        
        // 调用API更新游戏内容
        Api::getInstance()->updateGameContent(params, [=](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
            if (success) {
                // 更新成功
                QMessageBox::information(editDialog, "更新成功", "游戏内容更新成功！");
                editDialog->accept();
                
                // 刷新游戏内容列表
                this->updateGameContentTable();
            } else {
                // 更新失败
                QString errorMessage = errorMsg.isEmpty() ? "更新游戏内容失败，请稍后重试" : errorMsg;
                QMessageBox::warning(editDialog, "更新失败", errorMessage);
            }
        });
    });
    
    // 显示对话框
    if (editDialog->exec() == QDialog::Accepted) {
        // 对话框接受时的处理（已在回调中处理）
    }
    
    // 清理资源
    delete editDialog;
}

void content::on_deleteGameContentButton_clicked()
{
    // 获取选中的行
    QModelIndexList selectedRows = ui->gameContentTableWidget->selectionModel()->selectedRows();
    
    if (selectedRows.isEmpty()) {
        QMessageBox::warning(this, "提示", "请先选择要删除的游戏内容！");
        return;
    }
    
    // 获取选中行的游戏内容ID
    int selectedRow = selectedRows.first().row();
    QString contentId = ui->gameContentTableWidget->item(selectedRow, 0)->text();
    QString gameName = ui->gameContentTableWidget->item(selectedRow, 1)->text();
    
    // 显示确认对话框
    if (QMessageBox::question(this, "确认删除", 
                             QString("确定要删除游戏内容《%1》吗？此操作无法撤销。").arg(gameName),
                             QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
        return;
    }

    
    // 调用API删除游戏内容
    Api::getInstance()->deleteGameContent(contentId, [=](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {

        
        if (success) {
            // 删除成功
            QMessageBox::information(this, "删除成功", "游戏内容删除成功！");
            
            // 刷新游戏内容列表
            this->updateGameContentTable();
        } else {
            // 删除失败
            QString errorMessage = errorMsg.isEmpty() ? "删除游戏内容失败，请稍后重试" : errorMsg;
            QMessageBox::warning(this, "删除失败", errorMessage);
        }
    });
}

void content::on_gameContentSearchButton_clicked()
{
    // 获取搜索参数
    m_gameContentSearchKeyword = ui->gameContentSearchEdit->text().trimmed();
    m_gameContentSearchCategory = ui->gameCategoryComboBox->currentData().toString();
    m_gameContentSearchStatus = ui->gameStatusComboBox->currentData().toString();
    
    // 重置到第一页
    m_gameContentCurrentPage = 1;
    ui->gameContentPageSpinBox->setValue(m_gameContentCurrentPage);
    
    // 更新表格
    updateGameContentTable();
}

void content::on_gameContentResetButton_clicked()
{
    // 重置搜索参数
    ui->gameContentSearchEdit->clear();
    ui->gameCategoryComboBox->setCurrentIndex(0);
    ui->gameStatusComboBox->setCurrentIndex(0);
    
    m_gameContentSearchKeyword = "";
    m_gameContentSearchCategory = "";
    m_gameContentSearchStatus = "";
    
    // 重置到第一页
    m_gameContentCurrentPage = 1;
    ui->gameContentPageSpinBox->setValue(m_gameContentCurrentPage);
    
    // 更新表格
    updateGameContentTable();
}

void content::on_gameContentPrevPageButton_clicked()
{
    if (m_gameContentCurrentPage > 1) {
        m_gameContentCurrentPage--;
        ui->gameContentPageSpinBox->setValue(m_gameContentCurrentPage);
        updateGameContentTable();
    }
}

void content::on_gameContentNextPageButton_clicked()
{
    int totalPages = (m_gameContentTotalCount + m_gameContentPageSize - 1) / m_gameContentPageSize;
    if (m_gameContentCurrentPage < totalPages) {
        m_gameContentCurrentPage++;
        ui->gameContentPageSpinBox->setValue(m_gameContentCurrentPage);
        updateGameContentTable();
    }
}

void content::on_gameContentPageSpinBox_valueChanged(int value)
{
    if (value != m_gameContentCurrentPage && value > 0) {
        m_gameContentCurrentPage = value;
        updateGameContentTable();
    }
}

void content::on_gameContentPageSizeComboBox_currentIndexChanged(int index)
{
    // 根据索引获取页面大小
    int newPageSize = 10;
    switch (index) {
    case 0:
        newPageSize = 10;
        break;
    case 1:
        newPageSize = 20;
        break;
    case 2:
        newPageSize = 50;
        break;
    case 3:
        newPageSize = 100;
        break;
    default:
        newPageSize = 10;
        break;
    }
    
    // 只有当页面大小发生变化时才刷新数据
    if (newPageSize != m_gameContentPageSize) {
        m_gameContentPageSize = newPageSize;
        m_gameContentCurrentPage = 1; // 重置到第一页
        ui->gameContentPageSpinBox->setValue(m_gameContentCurrentPage);
        updateGameContentTable();
    }
}

// 公告管理相关槽函数
void content::on_addAnnouncementButton_clicked()
{
    // 创建添加公告对话框
    QDialog* addDialog = new QDialog(this);
    addDialog->setWindowTitle("添加公告");
    addDialog->resize(500, 400);
    
    // 创建布局
    QVBoxLayout* mainLayout = new QVBoxLayout(addDialog);
    
    // 创建表单布局
    QFormLayout* formLayout = new QFormLayout();
    
    // 公告标题
    QLineEdit* titleEdit = new QLineEdit();
    titleEdit->setPlaceholderText("请输入公告标题");
    formLayout->addRow("公告标题:", titleEdit);
    
    // 公告内容
    QTextEdit* contentEdit = new QTextEdit();
    contentEdit->setPlaceholderText("请输入公告内容");
    contentEdit->setMinimumHeight(150);
    formLayout->addRow("公告内容:", contentEdit);
    
    // 发布日期
    QDateEdit* publishDateEdit = new QDateEdit();
    publishDateEdit->setCalendarPopup(true);
    publishDateEdit->setDate(QDate::currentDate());
    formLayout->addRow("发布日期:", publishDateEdit);
    
    // 过期日期
    QDateEdit* expireDateEdit = new QDateEdit();
    expireDateEdit->setCalendarPopup(true);
    expireDateEdit->setDate(QDate::currentDate().addDays(7)); // 默认7天后过期
    formLayout->addRow("过期日期:", expireDateEdit);
    
    // 公告状态
    QComboBox* statusComboBox = new QComboBox();
    statusComboBox->addItem("已发布", "已发布");
    statusComboBox->addItem("草稿", "草稿");
    formLayout->addRow("公告状态:", statusComboBox);
    
    // 添加表单到主布局
    mainLayout->addLayout(formLayout);
    
    // 创建按钮布局
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    
    // 添加按钮
    QPushButton* confirmButton = new QPushButton("确认添加");
    QPushButton* cancelButton = new QPushButton("取消");
    
    buttonLayout->addWidget(confirmButton);
    buttonLayout->addWidget(cancelButton);
    
    mainLayout->addLayout(buttonLayout);
    
    // 连接取消按钮信号
    connect(cancelButton, &QPushButton::clicked, addDialog, &QDialog::reject);
    
    // 连接确认按钮信号
    connect(confirmButton, &QPushButton::clicked, [=]() {
        // 验证输入
        if (titleEdit->text().trimmed().isEmpty()) {
            QMessageBox::warning(addDialog, "输入错误", "公告标题不能为空！");
            titleEdit->setFocus();
            return;
        }
        
        if (contentEdit->toPlainText().trimmed().isEmpty()) {
            QMessageBox::warning(addDialog, "输入错误", "公告内容不能为空！");
            contentEdit->setFocus();
            return;
        }
        
        // 验证日期逻辑
        if (expireDateEdit->date() < publishDateEdit->date()) {
            QMessageBox::warning(addDialog, "输入错误", "过期日期不能早于发布日期！");
            expireDateEdit->setFocus();
            return;
        }
        
        // 准备参数
        QJsonObject params;
        params["title"] = titleEdit->text().trimmed();
        params["content"] = contentEdit->toPlainText().trimmed();
        params["publishDate"] = publishDateEdit->date().toString("yyyy-MM-dd");
        params["expireDate"] = expireDateEdit->date().toString("yyyy-MM-dd");
        params["status"] = statusComboBox->currentData().toString();
        
        // 调用API添加公告
        Api::getInstance()->addAnnouncement(params, [=](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
            if (success) {
                // 添加成功
                QMessageBox::information(addDialog, "添加成功", "公告添加成功！");
                addDialog->accept();
                
                // 刷新公告列表
                this->updateAnnouncementTable();
            } else {
                // 添加失败
                QString errorMessage = errorMsg.isEmpty() ? "添加公告失败，请稍后重试" : errorMsg;
                QMessageBox::warning(addDialog, "添加失败", errorMessage);
            }
        });
    });
    
    // 显示对话框
    if (addDialog->exec() == QDialog::Accepted) {
        // 对话框接受时的处理（已在回调中处理）
    }
    
    // 清理资源
    delete addDialog;
}

void content::on_editAnnouncementButton_clicked()
{
    // 获取选中的行
    QModelIndexList selectedRows = ui->announcementTableWidget->selectionModel()->selectedRows();
    
    if (selectedRows.isEmpty()) {
        QMessageBox::warning(this, "提示", "请先选择要编辑的公告！");
        return;
    }
    
    // 获取选中行的数据
    int selectedRow = selectedRows.first().row();
    QString announcementId = ui->announcementTableWidget->item(selectedRow, 0)->text();
    QString title = ui->announcementTableWidget->item(selectedRow, 1)->text();
    QString publishDate = ui->announcementTableWidget->item(selectedRow, 2)->text();
    QString expireDate = ui->announcementTableWidget->item(selectedRow, 3)->text();
    QString status = ui->announcementTableWidget->item(selectedRow, 4)->text();
    // 创建编辑对话框
    QDialog* editDialog = new QDialog(this);
    editDialog->setWindowTitle("编辑公告");
    editDialog->resize(600, 500);
    // 创建布局
    QVBoxLayout* mainLayout = new QVBoxLayout(editDialog);
    
    // 创建表单布局
    QFormLayout* formLayout = new QFormLayout();
    
    // 公告标题
    QLineEdit* titleEdit = new QLineEdit();
    titleEdit->setText(title);
    titleEdit->setPlaceholderText("请输入公告标题");
    formLayout->addRow("公告标题:", titleEdit);
    
    // 公告内容
    QTextEdit* contentEdit = new QTextEdit();
    contentEdit->setPlainText("");
    contentEdit->setPlaceholderText("请输入公告内容");
    contentEdit->setMinimumHeight(150);
    formLayout->addRow("公告内容:", contentEdit);
    
    // 发布日期
    QDateEdit* publishDateEdit = new QDateEdit();
    publishDateEdit->setCalendarPopup(true);
    QDate pubDate = QDate::fromString(publishDate, "yyyy-MM-dd");
    if (pubDate.isValid()) {
        publishDateEdit->setDate(pubDate);
    } else {
        publishDateEdit->setDate(QDate::currentDate());
    }
    formLayout->addRow("发布日期:", publishDateEdit);
    
    // 过期日期
    QDateEdit* expireDateEdit = new QDateEdit();
    expireDateEdit->setCalendarPopup(true);
    if (!expireDate.isEmpty()) {
        QDate expDate = QDate::fromString(expireDate, "yyyy-MM-dd");
        if (expDate.isValid()) {
            expireDateEdit->setDate(expDate);
        } else {
            expireDateEdit->setDate(QDate::currentDate().addDays(30)); // 默认30天后过期
        }
    } else {
        expireDateEdit->setDate(QDate::currentDate().addDays(30)); // 默认30天后过期
    }
    formLayout->addRow("过期日期:", expireDateEdit);
    
    // 公告状态
    QComboBox* statusComboBox = new QComboBox();
    statusComboBox->addItem("已发布", "published");
    statusComboBox->addItem("草稿", "draft");
    statusComboBox->addItem("已归档", "archived");
    // 设置当前选中的状态
    for (int i = 0; i < statusComboBox->count(); i++) {
        if (statusComboBox->itemData(i).toString() == status) {
            statusComboBox->setCurrentIndex(i);
            break;
        }
    }
    formLayout->addRow("公告状态:", statusComboBox);
    
    // 添加表单到主布局
    mainLayout->addLayout(formLayout);
    
    // 创建按钮布局
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    
    // 添加按钮
    QPushButton* confirmButton = new QPushButton("确认修改");
    QPushButton* cancelButton = new QPushButton("取消");
    
    buttonLayout->addWidget(confirmButton);
    buttonLayout->addWidget(cancelButton);
    
    mainLayout->addLayout(buttonLayout);
    
    // 连接取消按钮信号
    connect(cancelButton, &QPushButton::clicked, editDialog, &QDialog::reject);
    
    // 连接确认按钮信号
    connect(confirmButton, &QPushButton::clicked, [=]() {
        // 验证输入
        if (titleEdit->text().trimmed().isEmpty()) {
            QMessageBox::warning(editDialog, "输入错误", "公告标题不能为空！");
            titleEdit->setFocus();
            return;
        }
        
        if (contentEdit->toPlainText().trimmed().isEmpty()) {
            QMessageBox::warning(editDialog, "输入错误", "公告内容不能为空！");
            contentEdit->setFocus();
            return;
        }
        
        // 验证日期
        if (expireDateEdit->date() < publishDateEdit->date()) {
            QMessageBox::warning(editDialog, "日期错误", "过期日期不能早于发布日期！");
            expireDateEdit->setFocus();
            return;
        }
        
        // 准备参数
        QJsonObject params;
        params["id"] = announcementId;
        params["title"] = titleEdit->text().trimmed();
        params["content"] = contentEdit->toPlainText().trimmed();
        params["publishDate"] = publishDateEdit->date().toString("yyyy-MM-dd");
        params["expireDate"] = expireDateEdit->date().toString("yyyy-MM-dd");
        params["status"] = statusComboBox->currentData().toString();
        
        // 调用API更新公告
        Api::getInstance()->updateAnnouncement(params, [=](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
            if (success) {
                // 更新成功
                QMessageBox::information(editDialog, "更新成功", "公告更新成功！");
                editDialog->accept();
                
                // 刷新公告列表
                this->updateAnnouncementTable();
            } else {
                // 更新失败
                QString errorMessage = errorMsg.isEmpty() ? "更新公告失败，请稍后重试" : errorMsg;
                QMessageBox::warning(editDialog, "更新失败", errorMessage);
            }
        });
    });
    
    // 显示对话框
    if (editDialog->exec() == QDialog::Accepted) {
        // 对话框接受时的处理（已在回调中处理）
    }
    
    // 清理资源
    delete editDialog;
}

void content::on_deleteAnnouncementButton_clicked()
{
    // 获取选中的行
    QModelIndexList selectedRows = ui->announcementTableWidget->selectionModel()->selectedRows();
    
    if (selectedRows.isEmpty()) {
        QMessageBox::warning(this, "提示", "请先选择要删除的公告！");
        return;
    }
    
    // 获取选中行的公告ID和标题
    int selectedRow = selectedRows.first().row();
    QString announcementId = ui->announcementTableWidget->item(selectedRow, 0)->text();
    QString title = ui->announcementTableWidget->item(selectedRow, 1)->text();
    
    // 显示确认对话框
    if (QMessageBox::question(this, "确认删除", 
                             QString("确定要删除公告《%1》吗？此操作无法撤销。").arg(title),
                             QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
        return;
    }

    // 调用API删除公告
    Api::getInstance()->deleteAnnouncement(announcementId, [=](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success) {
            // 删除成功
            QMessageBox::information(this, "删除成功", "公告删除成功！");
            
            // 刷新公告列表
            this->updateAnnouncementTable();
        } else {
            // 删除失败
            QString errorMessage = errorMsg.isEmpty() ? "删除公告失败，请稍后重试" : errorMsg;
            QMessageBox::warning(this, "删除失败", errorMessage);
        }
    });
}

void content::on_announcementSearchButton_clicked()
{
    // 保存搜索参数
    m_announcementSearchKeyword = ui->announcementSearchEdit->text();
    m_announcementSearchStatus = ui->announcementStatusComboBox->currentText();
    
    // 搜索时重置为第一页
    m_announcementCurrentPage = 1;
    ui->announcementPageSpinBox->setValue(m_announcementCurrentPage);
    
    // 更新表格和分页信息
    updateAnnouncementTable();
    updateAnnouncementPaginationInfo();
}

void content::on_announcementResetButton_clicked()
{
    // TODO: 实现公告搜索重置功能
    updateAnnouncementTable();
}

void content::on_announcementPrevPageButton_clicked()
{
    // 实现公告上一页功能
    if (m_announcementCurrentPage > 1) {
        m_announcementCurrentPage--;
        ui->announcementPageSpinBox->setValue(m_announcementCurrentPage);
        updateAnnouncementTable();
    }
}

void content::on_announcementNextPageButton_clicked()
{
    // 实现公告下一页功能
    int totalPages = (m_announcementTotalCount + m_announcementPageSize - 1) / m_announcementPageSize;
    if (m_announcementCurrentPage < totalPages) {
        m_announcementCurrentPage++;
        ui->announcementPageSpinBox->setValue(m_announcementCurrentPage);
        updateAnnouncementTable();
    }
}

void content::on_announcementPageSpinBox_valueChanged(int value)
{
    // 实现公告页码变化功能
    int totalPages = (m_announcementTotalCount + m_announcementPageSize - 1) / m_announcementPageSize;
    if (value >= 1 && value <= totalPages && value != m_announcementCurrentPage) {
        m_announcementCurrentPage = value;
        updateAnnouncementTable();
    }
}

void content::on_announcementPageSizeComboBox_currentIndexChanged(int index)
{
    // 根据索引获取页面大小
    int newPageSize = m_announcementPageSize;
    switch (index) {
    case 0:
        newPageSize = 10;
        break;
    case 1:
        newPageSize = 20;
        break;
    case 2:
        newPageSize = 50;
        break;
    default:
        newPageSize = 10;
        break;
    }
    
    // 如果页面大小发生变化，重置到第一页
    if (newPageSize != m_announcementPageSize) {
        m_announcementPageSize = newPageSize;
        m_announcementCurrentPage = 1;
        ui->announcementPageSpinBox->setValue(m_announcementCurrentPage);
        updateAnnouncementTable();
    }
}


// 标签页切换槽函数
void content::on_mainTabWidget_currentChanged(int index)
{
    // 标签页切换时可以添加相应逻辑
    if (index == 0) {
        // 游戏内容标签页
        updateGameContentTable();
    } else if (index == 1) {
        // 公告管理标签页
        updateAnnouncementTable();
    }
}
